package com.example.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.reggie.mapper.ShoppingCartMapper;
import com.example.reggie.entity.ShoppingCart;
import com.example.reggie.service.ShoppingCartService;
import com.example.reggie.utils.BaseContext;
import com.example.reggie.utils.R;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {
    @Override
    public ShoppingCart add(ShoppingCart shoppingCart) {
        shoppingCart.setUserId(BaseContext.getId());
        shoppingCart.setCreateTime(LocalDateTime.now());
        shoppingCart.setNumber(1);
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,shoppingCart.getUserId());
        lqw.eq(shoppingCart.getDishId() != null,ShoppingCart::getDishId,shoppingCart.getDishId());
        lqw.eq(shoppingCart.getSetmealId() != null,ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        ShoppingCart one = getOne(lqw);
        if (one != null){
            one.setNumber(one.getNumber()+shoppingCart.getNumber());
            updateById(one);
            return one;
        }
        one = shoppingCart;
        save(one);
        return one;
    }

    @Override
    public List<ShoppingCart> listByUser() {
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper();
        lqw.eq(ShoppingCart::getUserId,BaseContext.getId());
        lqw.orderByDesc(ShoppingCart::getCreateTime);
        List<ShoppingCart> list = list(lqw);
        return list;
    }

    @Override
    public ShoppingCart sub(ShoppingCart shoppingCart) {
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(shoppingCart.getDishId() != null,ShoppingCart::getDishId,shoppingCart.getDishId());
        lqw.eq(shoppingCart.getSetmealId() != null,ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        ShoppingCart one = getOne(lqw);
        if (one.getNumber() == 1){
            one.setNumber(one.getNumber() - 1);
            remove(lqw);
        }else {
            one.setNumber(one.getNumber() - 1);
            updateById(one);
        }
        return one;
    }

    @Override
    public void clean() {
        Long userId = BaseContext.getId();
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,userId);
        remove(lqw);
    }
}
